using UnityEngine;

public class ExplosiveController : MonoBehaviour
{
    private CircleCollider2D cc;
    private CharacterStats stats;
    private Animator animator;
    private float growSpeed = 15f;
    private float maxSize = 6f;
    private float explosiveRadius;
    private bool canGrow = true;

    private void Awake()
    {
        cc = GetComponent<CircleCollider2D>();
        animator = GetComponent<Animator>();
    }

    void Update()
    {
        if (canGrow)
        {
            transform.localScale = Vector2.Lerp(transform.localScale, new Vector2(maxSize, maxSize), growSpeed * Time.deltaTime);
        }
        if (maxSize - transform.localScale.x < 0.5f)
        {
            canGrow = false;
            animator.SetTrigger("explode");
        }
    }

    public void Setup(CharacterStats stats, float growSpeed, float maxSize, float explosiveRadius)
    {
        this.stats = stats;
        this.growSpeed = growSpeed;
        this.maxSize = maxSize;
        this.explosiveRadius = explosiveRadius;
    }

    private void AnimationExplodeEvent()
    {
        Collider2D[] results = new Collider2D[10];
        var size = Physics2D.OverlapCircleNonAlloc(transform.position, explosiveRadius, results, LayerMask.NameToLayer("Player"));
        for (int i = 0; i < size; i++)
        {
            if (!results[i].TryGetComponent(out Entity entity)) continue;
            entity.SetupKnockbackDirection(transform.position);
            stats.DoDamage(entity.Stats);
        }
    }

    private void SelfDestory()
    {
        Destroy(gameObject);
    }
}
